#include "AudioInMgr.h"
#include "mediaPriv.h"

namespace Media{

std::map<int, AudioInMgr *>  AudioInMgr::sm_objectMap;
std::recursive_mutex 		 AudioInMgr::sm_mapMutex;

AudioInMgr *AudioInMgr::instance(int channel)
{
    if(channel > ADEC_SUPPORT_CHN - 1)
    {
        errorf("channel is over ADEC_SUPPORT_CHN \n");
        return NULL;
    }
    
    std::lock_guard<std::recursive_mutex> guard(sm_mapMutex);
    
	if(sm_objectMap.find(channel) == sm_objectMap.end())
	{
		sm_objectMap[channel] = new AudioInMgr(channel);
	}

	return sm_objectMap[channel];
}

AudioInMgr::AudioInMgr(int channel) 
{
    memset(&m_format, 0, sizeof(m_format));
}

bool AudioInMgr::createAudioIn(AudioInDesc inDesc)
{
    int status = 0;

    status = createAudioInput(&inDesc, &m_audioInObj);
    if (status)
    {
        return false;
    }

    return true;
}

bool AudioInMgr::setFormat(AudioInAttr format)
{
    if(!m_audioInObj)
	{
	    errorf("format or m_audioInObj is NULL \n");
		return false;
	}
		
    return (m_audioInObj->setChnAttr(m_audioInObj, format) >= 0);
}

bool AudioInMgr::start()
{
    if(!m_audioInObj)
	{
	    errorf("m_audioInObj is NULL \n");
		return false;
	}
    if(!m_started)
    {
        int ret = m_audioInObj->start(m_audioInObj);
    	if(ret)
    	{
    		return false;
    	}
    	m_started = true;
    }

	return true;
}

bool AudioInMgr::stop()
{
    if(!m_audioInObj)
	{
	    errorf("m_audioInObj is NULL \n");
		return false;
	}
	if(m_started)
    {
        int ret = m_audioInObj->stop(m_audioInObj);
    	if(ret)
    	{
    		return false;
    	}
    	m_started = false;
    }
	return true;
}

bool AudioInMgr::putPacket(AudioInPacket *packet)
{
    if(!packet || !m_audioInObj)
	{
	    errorf("packet or m_audioInObj NULL \n");
		return false;
	}
		
    return (m_audioInObj->putPacket(m_audioInObj,packet) >= 0);
}

}

